import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

Vue.config.productionTip = false

let baseUrl = 'http://localhost:1000/'
Vue.prototype.$baseUrl = baseUrl

axios.interceptors.request.use(config=>{
	console.log(config);
	let token = localStorage.getItem("token") || '';
	console.log(token);
	// let userInfo = JSON.parse(token);
	config.headers['token'] = token;
	return config;
},err=>{
	router.push("/")
	return Promise.reject(err);
})

//http response 拦截器
axios.interceptors.response.use(response=>{
	console.log("response",response)
	console.log("requestUrl:"+response.config.url);
	console.log("responseData",response.data.data);
	return response;
},err=>{
	console.log(err);
	router.push("/")
	return Promise.reject(err.response.status);
});

router.beforeEach((to,from,next)=>{
	// console.log(to,from,next);

	//判断是否登录
	let userInfo = store.state.userInfo;
	// console.log("userInfo:",userInfo)
	if(to.path!='/' && (!userInfo || !userInfo.username)){
		next({
			path: '/'
		});
	}

	if(to.path=='/index'){

		let indexChildrenRouters = [];
		axios.get(baseUrl+'menu/getTreeMenus').then(res=>{
			let menuData = res.data.data;
			menuData.forEach(menu=>{
				let subMenuList = menu.subMenu;
				subMenuList.forEach(subMenu=>{
					let newRouter = {
						name: subMenu.name,
						path: subMenu.path
					}
					newRouter.component = () => import( './views/'+subMenu.component+'.vue');
					indexChildrenRouters.push(newRouter);
				})
			})

			//欢迎页
			let helloRouter = {
				name: "权限管理系统",
				path: "/helloWorld"
			}
			helloRouter.component = () => import( './components/HelloWorld.vue');
			indexChildrenRouters.push(helloRouter);

			router.options.routes[0].children = indexChildrenRouters;
			router.addRoutes(router.options.routes);
		})

	}
	next();
})

new Vue({
	router,
	store,
	render: h => h(App)
}).$mount('#app')
